package com.jieao.generator.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jieao.common.constant.APIConstants;
import com.jieao.common.constant.SmsConstants;
import com.jieao.common.core.domain.AjaxResult;
import com.jieao.common.core.text.Convert;
import com.jieao.framework.util.ShiroUtils;
import com.jieao.generator.domain.SmsHistory;
import com.jieao.generator.domain.SmsTemp;
import com.jieao.generator.dto.SmsSendDto;
import com.jieao.generator.mapper.SmsHistoryMapper;
import com.jieao.generator.mapper.SmsTempMapper;
import com.jieao.generator.service.ISmsService;
import com.jieao.generator.util.HttpUtils;
import com.jieao.system.utils.DictUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author weifanl
 * @Date2020/7/20 12:33
 **/
@Service
@Slf4j
public class SmsServiceImpl extends ServiceImpl<SmsTempMapper, SmsTemp> implements ISmsService {
    @Autowired
    private SmsHistoryMapper historyMapper;
    @Override
    public List<SmsTemp> selectSmsTempList(SmsTemp smsTemp) {
        return baseMapper.selectSmsTempList(smsTemp);
    }

    @Override
    public Integer insertSmsTemp(SmsTemp smsTemp) {
        //调用添加模板接口
        smsTemp.setCreateBy(ShiroUtils.getLoginName());
        addTemp(smsTemp);
        Integer insert = null;
        try {
            insert = baseMapper.insert(smsTemp);
        } catch (Exception e) {
            log.info("模板添加失败,请求参数："+JSONObject.toJSONString(smsTemp));
        }
        return  insert;
    }

    @Override
    public SmsTemp selectSmsTempById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public Integer updateSmsTemp(SmsTemp smsTemp) {
        return baseMapper.updateById(smsTemp);
    }

    @Override
    public Integer deleteSmsTempByIds(String ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(ids)));
    }
    /**
     * @param smsSend
     * @return {void}
     * @author LWF
     * @date 2020/7/20 14:44
     **/
    @Override
    public AjaxResult send(SmsSendDto smsSend){
        if(null == smsSend.getModuleId() || null == smsSend.getPhone() || null == smsSend.getParams()){
            return AjaxResult.fail("参数不全");
        }
        SmsTemp smsTemp = baseMapper.selectById(smsSend.getModuleId());
        if(null == smsTemp || !smsTemp.getStatus().equals(SmsConstants.SMS_VERIFY_99)){
            return AjaxResult.error("未找到模板或模板未审核通过");
        }
        String path = "/sms/sendv2";
        String method = "GET";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + APIConstants.SMS_APP_CODE);

        //解析模板中的参数
        String content = smsTemp.getContent();
        Map<String, String> params = smsSend.getParams();
        for(String key : params.keySet()){
            content = content.replace("#"+key+"#",params.get(key));
        }
        Map<String, String> querys = new HashMap<>();
        querys.put("mobile", smsSend.getPhone());
        querys.put("content", "【"+smsTemp.getSignature()+"】"+content);

        try {
            HttpResponse response = HttpUtils.doGet(APIConstants.SMS_URL, path, method, headers, querys);
            HttpEntity entity = response.getEntity();
            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(entity,"UTF-8"));

            Object code = jsonObject.get("error_code");
            if(null != code && Integer.parseInt(code.toString()) == 0 && jsonObject.get("result") != null){
                SmsHistory history = new SmsHistory();
                history.setId(Long.parseLong(jsonObject.get("result").toString()));
                history.setTempId(smsTemp.getId());
                history.setPhone(smsSend.getPhone());
                history.setContent(content);
                historyMapper.insert(history);
                return AjaxResult.success("发送成功");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.fail("发送失败");
    }
    /**
     * 添加短信模板
     * @param smsTemp
     * @return {void}
     * @author LWF
     * @date 2020/7/21 15:34
     **/
    private void addTemp(SmsTemp smsTemp){
        String path = "/sms/edittemplete";
        String method = "POST";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + APIConstants.SMS_APP_CODE);

        Map<String, String> querys = new HashMap<>();
        querys.put("content", smsTemp.getContent());
        querys.put("signature", smsTemp.getSignature());
        Map<String, String> bodys = new HashMap<>();

        try {
            HttpResponse response = HttpUtils.doPost(APIConstants.SMS_URL, path, method, headers, querys, bodys);
            HttpEntity entity = response.getEntity();
            if(entity!=null){
                String result = EntityUtils.toString(entity,"UTF-8");

                JSONObject jsonObject = JSONObject.parseObject(result);
                Object code = jsonObject.get("error_code");
                if(null != code && Integer.parseInt(code.toString()) == 0 && jsonObject.get("result") != null){
                    smsTemp.setId(Long.parseLong(jsonObject.get("result").toString()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public AjaxResult refreshTempStatus(){
        String path = "/sms/gettempletestatus";
        String method = "GET";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + APIConstants.SMS_APP_CODE);

        List<SmsTemp> smsTemps = baseMapper.selectList(Wrappers.<SmsTemp>query().lambda().eq(SmsTemp::getStatus, 0));

        Map<String, String> querys = new HashMap<String, String>();
        for(SmsTemp temp : smsTemps){
            querys.put("templateId", temp.getId().toString());

            try {
                HttpResponse response = HttpUtils.doGet(APIConstants.SMS_URL, path, method, headers, querys);

                HttpEntity entity = response.getEntity();
                if(entity!=null){
                    String result = EntityUtils.toString(entity,"UTF-8");

                    JSONObject jsonObject = JSONObject.parseObject(result);
                    Object code = jsonObject.get("error_code");
                    if(null != code && Integer.parseInt(code.toString()) == 0 && jsonObject.get("result") != null){
                        JSONObject jsonObject1 = jsonObject.getJSONObject("result");
                        Integer status = Integer.parseInt(jsonObject1.get("Status").toString());
                        status = (status == 1? 99 : status);
                        status = (status == 2? 98 : status);
                        temp.setStatus(status);
                        temp.setRemark(jsonObject1.get("NotPassReason")==null?"":jsonObject1.get("NotPassReason").toString());
                        baseMapper.updateById(temp);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //同步到数据库
        /*Map<Long, SmsTemp> collect = smsTemps.stream().collect(Collectors.toMap(SmsTemp::getId, dto -> dto));

        String path1 = "/sms/tmplist";
        Map<String, String> querys1 = new HashMap<String, String>();
        try {
            HttpResponse response = HttpUtils.doGet(APIConstants.SMS_URL, path1, method, headers, querys1);

            String result = EntityUtils.toString(response.getEntity(),"UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONArray result1 = jsonObject.getJSONArray("result");
            for(int i=0;i<result1.size();i++){
                JSONObject o = (JSONObject)result1.get(i);
                if(null == collect.get(o.get("Id"))){
                    SmsTemp smsTemp = new SmsTemp();
                    smsTemp.setId(Long.parseLong(o.get("Id").toString()));
                    smsTemp.setStatus(Integer.parseInt(o.get("Status").toString()));
                    smsTemp.setContent(o.get("TContent").toString());
                    smsTemp.setRemark(o.get("NotPassReason")==null?"":o.get("NotPassReason").toString());
                    try {
                        baseMapper.insert(smsTemp);
                    } catch (Exception e) {}
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }*/

        return AjaxResult.success("更新成功");
    }

}
